const userWork = require('@koa/router')()
const DB = require('../controllers/db')
const tk = require('../utils/token')

userWork.post('/', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      const msg = await DB.userWorks(ctx.request.body.userName, ctx.request.header.token)
      ctx.body = msg
    }
  }
})

userWork.post('/delete', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      const msg = await DB.deleteUserWork(ctx.request.body.videoId)
      ctx.body = msg
    }
  }
})

userWork.post('/add', async (ctx, next) => {
  if (!ctx.request.header.token) {
    ctx.body = {
      code: 409,
      msg: `未携带令牌`
    }
  } else {
    if (!await tk.trueToken(ctx.request.header.token)) {
      ctx.body = {
        code: 400,
        data: {
          msg: `用户验证过期`
        }
      }
    } else {
      if (ctx.request.body.title && 
        ctx.request.body.author &&  
        ctx.request.body.videoUrl && 
        ctx.request.body.cover && 
        ctx.request.body.description) {
        const msg = await DB.addUserWork(
          ctx.request.body.title, 
          ctx.request.body.author, 
          ctx.request.body.videoUrl, 
          ctx.request.body.cover, 
          ctx.request.body.description)
        ctx.body = msg
      } else {
        ctx.body = {
          code: 408,
          msg: `未携带必要参数`
        }
      }
    }
  }
})



module.exports = userWork